package com.iotechn.unimall.app.api.plantgoods;

import com.baomidou.mybatisplus.entity.Column;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.annotation.HttpMethod;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.PlantGoodsHistoryDO;
import com.iotechn.unimall.data.enums.StatusType;
import com.iotechn.unimall.data.mapper.PlantGoodsCategoryMapper;
import com.iotechn.unimall.data.mapper.PlantGoodsHistoryMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by rize on 2019/7/2.
 */
@Service
public class PlantGoodsHistoryServiceImpl implements PlantGoodsHistoryService {
    @Autowired
    private PlantGoodsHistoryMapper plantGoodsHistoryMapper;
    @Autowired
    private PlantGoodsCategoryMapper plantGoodsCategoryMapper;

    @Autowired
    private CacheComponent cacheComponent;

    public static final String CA_PLANTGOODS_PAGE_PREFIX = "CA_PLANTGOODS_PAGE_";


    private static final Column[] baseColumns = {
            Column.create().column("id"),
            Column.create().column("avg_price").as("avgPrice"),
            Column.create().column("title"),
            Column.create().column("unit"),
            Column.create().column("img"),
            Column.create().column("gmt_day").as("gmtDay"),
            Column.create().column("category_id").as("categoryId"),
            Column.create().column("status")};

    public Page<PlantGoodsHistoryDO> getPlantGoodsHistoryPage(Integer pageNo, Integer pageSize, Long categoryId, String orderBy, Boolean isAsc, String title) throws ServiceException {
        Wrapper<PlantGoodsHistoryDO> wrapper = new EntityWrapper<PlantGoodsHistoryDO>();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        } else {
            //若关键字为空，尝试从缓存取列表
            Page objFromCache = cacheComponent.getObj(CA_PLANTGOODS_PAGE_PREFIX + categoryId + "_" + pageNo + "_" + pageSize + "_" + orderBy + "_" + isAsc, Page.class);
            if (objFromCache != null) {
                return objFromCache;
            }
        }

        if (orderBy != null && isAsc != null) {
            wrapper.orderBy(orderBy, isAsc);
        }

        if (categoryId != null && categoryId != 0L) {
            wrapper.eq("category_id", categoryId);
        }

        wrapper.eq("status", StatusType.ACTIVE.getCode());
        wrapper.setSqlSelect(baseColumns);
        List<PlantGoodsHistoryDO> spuDOS = plantGoodsHistoryMapper.selectPage(new RowBounds((pageNo - 1) * pageSize, pageSize), wrapper);

        Integer count = plantGoodsHistoryMapper.selectCount(wrapper);
        Page<PlantGoodsHistoryDO> page = new Page<>(spuDOS, pageNo, pageSize, count);
        if (StringUtils.isEmpty(title)) {
            //若关键字为空，制作缓存
            cacheComponent.putObj(CA_PLANTGOODS_PAGE_PREFIX + categoryId + "_" + pageNo + "_" + pageSize + "_" + orderBy + "_" + isAsc, page, Const.CACHE_ONE_DAY);
        }
        return page;
    }

    @HttpMethod(description = "搜索商品")
    public List<PlantGoodsHistoryDO> getPlantGoodsHistoryList(Integer pageNo, Integer pageSize) throws ServiceException {
        Wrapper<PlantGoodsHistoryDO> wrapper = new EntityWrapper<PlantGoodsHistoryDO>();

        //若关键字为空，尝试从缓存取列表
        List objFromCache = cacheComponent.getObj(CA_PLANTGOODS_PAGE_PREFIX + "_" + pageNo + "_" + pageSize + "_false", List.class);
        if (objFromCache != null) {
            return objFromCache;
        }
        wrapper.eq("status", StatusType.ACTIVE.getCode());
        wrapper.setSqlSelect(baseColumns);
        List<PlantGoodsHistoryDO> spuDOS = plantGoodsHistoryMapper.selectPage(new RowBounds((pageNo - 1) * pageSize, pageSize), wrapper);
        cacheComponent.putObj(CA_PLANTGOODS_PAGE_PREFIX + "_" + pageNo + "_" + pageSize + "_" + "_false", spuDOS, Const.CACHE_ONE_DAY);
        return spuDOS;
    }

    @HttpMethod(description = "单品三个月的价格情况")
    public List<PlantGoodsHistoryDO> getPlantGoodsHistoryListById(String title) throws ServiceException {
        Wrapper<PlantGoodsHistoryDO> wrapper = new EntityWrapper<PlantGoodsHistoryDO>();

        //若关键字为空，尝试从缓存取列表
        List objFromCache = cacheComponent.getObj(CA_PLANTGOODS_PAGE_PREFIX + "_plantGoodsId_" + title, List.class);
        if (objFromCache != null) {
            return objFromCache;
        }
        wrapper.eq("title", title);
        wrapper.eq("status", StatusType.ACTIVE.getCode());
        wrapper.setSqlSelect(baseColumns);
        Integer days = 90;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String gmtStart = sdf.format(new Date(System.currentTimeMillis() - 1000l * 60 * 60 * 24 * days));
        String gmtEnd = sdf.format(new Date());
        wrapper.between("gmt_day", gmtStart, gmtEnd);
        List<String> orderAsc = new ArrayList<>();
        orderAsc.add("gmt_day");
        wrapper.orderAsc(orderAsc);
        List<PlantGoodsHistoryDO> spuDOS = plantGoodsHistoryMapper.selectList(wrapper);
        cacheComponent.putObj(CA_PLANTGOODS_PAGE_PREFIX + "_plantGoodsId_" + title, spuDOS, Const.CACHE_ONE_DAY);
        return spuDOS;
    }

}
